//
//  HexKeyboard.swift
//  HexKeyboard
//
//  Created by LevinYan on 16/5/6.
//  Copyright © 2016年 LevinYan. All rights reserved.
//

import UIKit

class HexKeyboard: UIView {

    weak var textField:UITextField!
    let height = CGFloat(300)
    let width = UIScreen.mainScreen().bounds.width
    let buttonTag = ["D","E","F","A","B","C","7","8","9","4","5","6","1","2","3","DEL","0","Done"]
    let rowCount = 6
    let columnCount = 3
    init(textField:UITextField){
        self.textField = textField
        super.init(frame: CGRectMake(0, UIScreen.mainScreen().bounds.height - height, width, height))
        self.initAppearance()
    }
    
    func initAppearance() {
      
      
        let buttonHeight = self.height/CGFloat(self.rowCount)
        let buttonWidth = self.width/CGFloat(self.columnCount)
        let margin = CGFloat(0.5)
        for row in 0...self.rowCount-1{
        
            for column in 0...self.columnCount-1{
                
                let button = UIButton(type: UIButtonType.System)
                button.frame = CGRectMake(CGFloat(column)*buttonWidth + margin, CGFloat(row)*buttonHeight + margin, buttonWidth - 2*margin, buttonHeight - 2*margin)
                button.setTitle(self.buttonTag[row*columnCount + column], forState:UIControlState.Normal)
                button.titleLabel?.font = UIFont.systemFontOfSize(20)
                button.layer.cornerRadius = 10;
                button.clipsToBounds = true;
                button.layer.borderWidth = 1
                button.layer.borderColor = UIColor.grayColor().CGColor
                button.tag = row*columnCount + column
                
                button.addTarget(self, action: #selector(HexKeyboard.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
                self.addSubview(button)
            }
            
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func buttonClicked(button:UIButton) {
        let tag = self.buttonTag[button.tag]
        
        switch tag {
        case "DEL":
            if self.textField.text?.characters.count > 0{
                self.textField.text = self.textField.text?.substringToIndex(self.textField.text!.endIndex.predecessor())
            }
            
        case "Done":
            self.textField.resignFirstResponder()
        default:
            self.textField.text = self.textField.text! + tag
            
        }
        
    }
}
